// Local data layer using wx storage. Works offline without server.

const STORAGE_KEYS = {
  USERS: "__SRS_USERS__",
  APPLICATIONS: "__SRS_APPLICATIONS__",
  SESSION: "__SRS_SESSION__",
};

function read(key, fallback) {
  const value = wx.getStorageSync(key);
  return value ? value : fallback;
}

function write(key, value) {
  wx.setStorageSync(key, value);
}

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function generateRandomCourses() {
  const coursePool = [
    "高等数学",
    "线性代数",
    "概率论与数理统计",
    "大学英语",
    "计算机网络",
    "数据结构",
    "操作系统",
    "数据库系统",
    "软件工程",
    "离散数学",
    "现代物理",
    "电路原理",
    "工程制图",
    "管理学基础",
    "经济学基础",
  ];
  const semesters = ["2023-2024-1", "2023-2024-2", "2024-2025-1"];
  const count = randomInt(6, 10);
  const used = new Set();
  const courses = [];
  for (let i = 0; i < count; i++) {
    let name = coursePool[randomInt(0, coursePool.length - 1)];
    // 避免完全重复
    let tries = 0;
    while (used.has(name) && tries < 5) {
      name = coursePool[randomInt(0, coursePool.length - 1)];
      tries++;
    }
    used.add(name);
    const credit = [2, 3, 4][randomInt(0, 2)];
    const score = randomInt(75, 98);
    const semester = semesters[randomInt(0, semesters.length - 1)];
    courses.push({ name, credit, score, semester });
  }
  return courses;
}

function computeGpa(courses) {
  // 简单 100 分转 4 分法：>=90:4.0, 85-89:3.7, 80-84:3.3, 75-79:3.0, 70-74:2.7, 60-69:2.0, else:0
  const toPoint = (s) =>
    s >= 90
      ? 4.0
      : s >= 85
      ? 3.7
      : s >= 80
      ? 3.3
      : s >= 75
      ? 3.0
      : s >= 70
      ? 2.7
      : s >= 60
      ? 2.0
      : 0;
  let totalCredits = 0;
  let weighted = 0;
  courses.forEach((c) => {
    totalCredits += c.credit;
    weighted += toPoint(c.score) * c.credit;
  });
  const gpa = totalCredits > 0 ? +(weighted / totalCredits).toFixed(2) : 0;
  return { gpa, totalCredits };
}

function generateRandomTranscript() {
  const courses = generateRandomCourses();
  const { gpa, totalCredits } = computeGpa(courses);
  return {
    gpa,
    totalCredits,
    courses,
    imageUrl: "",
    verified: false,
  };
}

// Auth
function registerUser(payload) {
  const users = read(STORAGE_KEYS.USERS, []);
  const exists = users.some(
    (u) => u.username === payload.username && u.userType === payload.userType
  );
  if (exists) {
    return { success: false, message: "账号已存在" };
  }

  const user = {
    id: `${Date.now()}`,
    username: payload.username,
    realName: payload.realName,
    userType: payload.userType,
    password: payload.password,
    profile:
      payload.userType === "student"
        ? {
            major: payload.major || "",
            grade: payload.grade || "",
            className: payload.className || "",
          }
        : {
            department: payload.department || "",
            position: payload.position || "",
          },
  };
  users.push(user);
  write(STORAGE_KEYS.USERS, users);

  // 学生注册时，初始化应用数据但不自动生成成绩单
  if (user.userType === "student") {
    const apps = read(STORAGE_KEYS.APPLICATIONS, {});
    const now = new Date().toISOString();
    apps[user.id] = {
      studentId: user.id,
      status: "draft",
      transcript: null,
      research: [],
      scores: {},
      updatedAt: now,
      createdAt: now,
    };
    write(STORAGE_KEYS.APPLICATIONS, apps);
  }
  return { success: true };
}

function login(payload) {
  const users = read(STORAGE_KEYS.USERS, []);
  const user = users.find(
    (u) =>
      u.username === payload.username &&
      u.userType === payload.userType &&
      u.password === payload.password
  );
  if (!user) {
    return { success: false, message: "用户名或密码错误" };
  }
  write(STORAGE_KEYS.SESSION, { userId: user.id, userType: user.userType });
  return {
    success: true,
    userInfo: {
      id: user.id,
      username: user.username,
      userType: user.userType,
      profile: user.profile,
      realName: user.realName,
    },
  };
}

function getCurrentUser() {
  const session = read(STORAGE_KEYS.SESSION, null);
  if (!session) return null;
  const users = read(STORAGE_KEYS.USERS, []);
  return users.find((u) => u.id === session.userId) || null;
}

// Student application
function getApplicationStatus() {
  const user = getCurrentUser();
  const apps = read(STORAGE_KEYS.APPLICATIONS, {});
  const app = apps[user?.id] || null;
  const status = app?.status || "pending";
  const canSubmit = !!(app?.transcript && (app?.research?.length || 0) > 0);
  const lastUpdateTime = app?.updatedAt || new Date().toISOString();
  return { success: true, data: { status, canSubmit, lastUpdateTime } };
}

function submitApplication() {
  const user = getCurrentUser();
  if (!user) return { success: false, message: "未登录" };
  const apps = read(STORAGE_KEYS.APPLICATIONS, {});
  const app = apps[user.id] || { research: [], transcript: null };
  app.status = "submitted";
  // 初始化三级审核流程阶段
  app.review = app.review || {
    stage: "collegeHouse", // 书院
    stages: {
      collegeHouse: { status: "pending", reviewer: "" },
      college: { status: "pending", reviewer: "" },
      university: { status: "pending", reviewer: "" },
    },
  };
  app.updatedAt = new Date().toISOString();
  apps[user.id] = app;
  write(STORAGE_KEYS.APPLICATIONS, apps);
  return { success: true };
}

module.exports = {
  registerUser,
  login,
  getCurrentUser,
  getApplicationStatus,
  submitApplication,
  // expose helpers for transcript
  generateRandomTranscript,
  getTranscriptList: function () {
    const user = getCurrentUser();
    if (!user) return { success: false, data: [] };
    const apps = read(STORAGE_KEYS.APPLICATIONS, {});
    const app = apps[user.id] || null;
    const t = app?.transcript || null;
    if (!t) return { success: true, data: [] };
    const item = {
      id: "current",
      semester: t.semester || "当前成绩单",
      gpa: t.gpa,
      courseCount: Array.isArray(t.courses) ? t.courses.length : 0,
      status: t.verified ? "verified" : "pending",
    };
    return { success: true, data: [item] };
  },
  saveTranscript: function (transcript) {
    const user = getCurrentUser();
    if (!user) return { success: false, message: "未登录" };
    const apps = read(STORAGE_KEYS.APPLICATIONS, {});
    const app = apps[user.id] || { research: [], transcript: null };

    // 处理OCR解析后的数据结构
    let processedTranscript;
    if (transcript.student && transcript.courses && transcript.summary) {
      // 新的OCR数据结构
      processedTranscript = {
        semester: "当前学期",
        gpa: transcript.summary.averageGPA || 0,
        totalCredits: transcript.summary.totalCredits || 0,
        courses: transcript.courses.map((course) => ({
          name: course.name,
          type: course.type,
          credit: course.credits, // 映射为credit字段以匹配编辑页面
          score: course.score,
          semester: course.semester || "当前学期",
        })),
        imageUrl: transcript.imageUrl || "",
        verified: false,
        // 保存学生信息
        studentInfo: {
          name: transcript.student.name,
          studentId: transcript.student.studentId,
          major: transcript.student.major,
          class: transcript.student.class,
          college: transcript.student.college,
        },
        // 保存汇总信息
        summary: transcript.summary,
      };
    } else {
      // 兼容旧的数据结构
      processedTranscript = {
        semester: transcript.semester || transcript.term || "当前学期",
        gpa: transcript.gpa,
        totalCredits: transcript.totalCredits,
        courses: transcript.courses || [],
        imageUrl: transcript.imageUrl || "",
        verified: !!transcript.verified,
      };
    }

    app.transcript = processedTranscript;
    app.updatedAt = new Date().toISOString();
    apps[user.id] = app;
    write(STORAGE_KEYS.APPLICATIONS, apps);
    return { success: true };
  },
  getTranscript: function () {
    const user = getCurrentUser();
    if (!user) return null;
    const apps = read(STORAGE_KEYS.APPLICATIONS, {});
    const app = apps[user.id] || null;
    return app?.transcript || null;
  },
  removeTranscript: function () {
    const user = getCurrentUser();
    if (!user) return { success: false, message: "未登录" };
    const apps = read(STORAGE_KEYS.APPLICATIONS, {});
    const app = apps[user.id] || { research: [], transcript: null };
    app.transcript = null;
    app.updatedAt = new Date().toISOString();
    apps[user.id] = app;
    write(STORAGE_KEYS.APPLICATIONS, apps);
    return { success: true };
  },
  // Research helpers
  getResearchList: function () {
    const user = getCurrentUser();
    if (!user) return { success: false, data: { list: [], stats: {} } };
    const apps = read(STORAGE_KEYS.APPLICATIONS, {});
    const app = apps[user.id] || { research: [] };
    const rawList = Array.isArray(app.research) ? app.research : [];

    // 处理科研成果数据，添加状态和类型名称
    const list = rawList.map((item) => {
      const typeNames = {
        paper: "论文",
        patent: "专利",
        award: "获奖",
        project: "项目",
      };

      const levelNames = {
        school: "校级",
        municipal: "市级",
        provincial: "省级",
        national: "国家级",
      };

      return {
        ...item,
        typeName: typeNames[item.type] || "其他",
        levelName: levelNames[item.level] || "其他",
        status: item.verified ? "verified" : "pending", // 添加状态字段
        role: item.role || "参与者", // 添加角色字段
        date: item.date || new Date().toLocaleDateString(), // 添加日期字段
        files: item.files || [], // 添加文件字段
      };
    });

    const total = list.length;
    const verified = list.filter((r) => r.verified).length;
    const pending = total - verified;
    const score = list.reduce((s, r) => s + (r.score || 0), 0);
    return {
      success: true,
      data: { list, stats: { total, verified, pending, score } },
    };
  },
  addResearch: function (item) {
    const user = getCurrentUser();
    if (!user) return { success: false, message: "未登录" };
    const apps = read(STORAGE_KEYS.APPLICATIONS, {});
    const app = apps[user.id] || { research: [], transcript: null };
    const research = app.research || [];
    const id = `${Date.now()}`;
    research.push({
      id,
      title: item.title || "",
      type: item.type || "paper",
      level: item.level || "school",
      description: item.description || "",
      evidence: item.evidence || "",
      score: item.score || 0,
      verified: false,
    });
    app.research = research;
    app.updatedAt = new Date().toISOString();
    apps[user.id] = app;
    write(STORAGE_KEYS.APPLICATIONS, apps);
    return { success: true, id };
  },
  updateResearch: function (id, data) {
    const user = getCurrentUser();
    if (!user) return { success: false, message: "未登录" };
    const apps = read(STORAGE_KEYS.APPLICATIONS, {});
    const app = apps[user.id] || { research: [] };
    app.research = (app.research || []).map((r) =>
      String(r.id || r._id) === String(id) ? { ...r, ...data } : r
    );
    app.updatedAt = new Date().toISOString();
    apps[user.id] = app;
    write(STORAGE_KEYS.APPLICATIONS, apps);
    return { success: true };
  },
  deleteResearch: function (id) {
    const user = getCurrentUser();
    if (!user) return { success: false, message: "未登录" };
    const apps = read(STORAGE_KEYS.APPLICATIONS, {});
    const app = apps[user.id] || { research: [] };
    const before = app.research.length;
    app.research = (app.research || []).filter((r, idx) => {
      const rid = r.id || r._id || `${idx}`;
      return String(rid) !== String(id);
    });
    app.updatedAt = new Date().toISOString();
    apps[user.id] = app;
    write(STORAGE_KEYS.APPLICATIONS, apps);
    return { success: true, removed: before - app.research.length };
  },
  // Application helpers
  getApplicationInfo: function () {
    const user = getCurrentUser();
    if (!user) return { success: false, data: {} };
    const apps = read(STORAGE_KEYS.APPLICATIONS, {});
    const app = apps[user.id] || {
      status: "draft",
      transcript: null,
      research: [],
      updatedAt: new Date().toISOString(),
    };

    // 计算评审结果
    let result = "";
    if (app.status === "completed") {
      // 检查是否所有阶段都通过
      const stages = app.review?.stages || {};
      const allApproved = ["collegeHouse", "college", "university"].every(
        (stage) => stages[stage]?.status === "approved"
      );
      result = allApproved ? "approved" : "rejected";
    }

    // 计算评审进度
    const stages = app.review?.stages || {};
    const progress = [
      {
        name: "书院审核",
        status: stages.collegeHouse?.status || "pending",
        step: 1,
        desc:
          stages.collegeHouse?.status === "approved"
            ? "已通过"
            : stages.collegeHouse?.status === "rejected"
            ? "已退回"
            : "待审核",
        time: stages.collegeHouse?.updatedAt || "",
      },
      {
        name: "学院审核",
        status: stages.college?.status || "pending",
        step: 2,
        desc:
          stages.college?.status === "approved"
            ? "已通过"
            : stages.college?.status === "rejected"
            ? "已退回"
            : "待审核",
        time: stages.college?.updatedAt || "",
      },
      {
        name: "学校审核",
        status: stages.university?.status || "pending",
        step: 3,
        desc:
          stages.university?.status === "approved"
            ? "已通过"
            : stages.university?.status === "rejected"
            ? "已退回"
            : "待审核",
        time: stages.university?.updatedAt || "",
      },
    ];

    return {
      success: true,
      data: {
        application: {
          status: app.status,
          updateTime: app.updatedAt,
          result: result,
          score: (app.scores && app.scores.total) || 0,
          feedback: "",
          reviewer: "",
        },
        progress: progress,
      },
    };
  },
  // Judge helpers
  _deptToStage: function (department) {
    if (department === "书院") return "collegeHouse";
    if (department === "学院") return "college";
    if (department === "学校") return "university";
    return "collegeHouse";
  },
  getMaterialsStatus: function () {
    const user = getCurrentUser();
    if (!user) return { success: false, data: {} };
    const apps = read(STORAGE_KEYS.APPLICATIONS, {});
    const app = apps[user.id] || { research: [], transcript: null };
    const profileOk = !!(
      user.profile &&
      (user.profile.major || user.profile.department)
    );
    const transcriptOk = !!app.transcript;
    const researchOk = !!(app.research && app.research.length > 0);
    return {
      success: true,
      data: {
        profile: profileOk,
        transcript: transcriptOk,
        research: researchOk,
      },
    };
  },
  _deptToStage: function (department) {
    if (department === "书院") return "collegeHouse";
    if (department === "学院") return "college";
    if (department === "学校") return "university";
    return "collegeHouse";
  },
  getJudgeApplications: function (filter = "all", department) {
    const user = getCurrentUser();
    if (!user || user.userType !== "judge") return { success: true, data: [] };
    const apps = read(STORAGE_KEYS.APPLICATIONS, {});
    const users = read(STORAGE_KEYS.USERS, []);
    console.log("申请数据键名:", Object.keys(apps));
    console.log(
      "用户数据:",
      users.map((u) => ({ id: u.id, username: u.username }))
    );
    const restrictStage = department ? this._deptToStage(department) : null;
    const list = Object.keys(apps)
      .map((sid) => {
        const a = apps[sid];
        const student = users.find((u) => u.id === sid) || {};
        const status = a.status || "draft";
        const stage = a.review?.stage || "collegeHouse";
        const stageStatus = a.review?.stages?.[stage]?.status || "pending";
        console.log(
          `申请 ${sid}: status=${status}, stage=${stage}, stageStatus=${stageStatus}, restrictStage=${restrictStage}`
        );
        // 只显示已提交的申请，不显示草稿
        if (status === "draft") {
          return null;
        }

        // 检查评委是否能看到这个申请
        if (restrictStage) {
          // 如果申请已完成或已退回，显示给所有评委
          if (status === "completed" || status === "rejected") {
            // 已完成的申请显示给所有评委，不需要额外检查
          } else if (status === "submitted") {
            // 对于待评审的申请，检查评委是否应该看到
            if (stage === restrictStage) {
              // 当前阶段匹配，检查上一阶段是否已通过
              const stageOrder = ["collegeHouse", "college", "university"];
              const currentIndex = stageOrder.indexOf(stage);
              if (currentIndex > 0) {
                const prevStage = stageOrder[currentIndex - 1];
                const prevStatus = a.review?.stages?.[prevStage]?.status;
                if (prevStatus !== "approved") {
                  return null; // 上一阶段未通过，不显示给当前评委
                }
              }
            } else {
              // 当前阶段不匹配，检查该评委是否曾经参与过
              const judgeStageStatus =
                a.review?.stages?.[restrictStage]?.status;
              if (!judgeStageStatus || judgeStageStatus === "pending") {
                return null; // 该评委没有参与过这个申请
              }
            }
          }
        }
        let statusText = "";
        if (status === "completed") statusText = "已评审";
        else if (status === "rejected") statusText = "已退回";
        else if (status === "submitted") {
          if (stageStatus === "pending") {
            // 根据阶段显示具体的待评审信息
            if (stage === "collegeHouse") statusText = "待书院评委评审";
            else if (stage === "college") statusText = "待学院评委评审";
            else if (stage === "university") statusText = "待学校评委评审";
            else statusText = "待评审";
          } else {
            statusText = "进行中";
          }
        } else if (status === "draft") statusText = "草稿";
        else statusText = status;
        return {
          id: sid,
          studentName: student.realName || student.username || "",
          studentId: student.username || "",
          major: (student.profile && student.profile.major) || "",
          gpa: a.transcript?.gpa || 0,
          transcriptCount: a.transcript ? 1 : 0,
          researchCount: Array.isArray(a.research) ? a.research.length : 0,
          status,
          statusText,
          stage,
          review: a.review,
          submitTime: a.updatedAt || "",
          score: a.scores?.total || 0,
        };
      })
      .filter(Boolean);
    const filtered = list.filter((item) => {
      if (filter === "all") return true;
      if (filter === "pending") {
        // 待评审：只显示当前阶段需要评审的申请
        return (
          item.status === "submitted" &&
          item.statusText.includes("待") &&
          item.statusText.includes("评审") &&
          (restrictStage ? item.stage === restrictStage : true)
        );
      }
      if (filter === "completed") {
        // 已评审：显示该评委已经评审过的申请
        if (restrictStage) {
          const judgeStageStatus = item.review?.stages?.[restrictStage]?.status;
          return (
            judgeStageStatus === "approved" || judgeStageStatus === "rejected"
          );
        }
        return item.status === "completed";
      }
      return true;
    });
    return { success: true, data: filtered };
  },
  judgeUpdateStage: function (studentId, action) {
    const apps = read(STORAGE_KEYS.APPLICATIONS, {});
    const app = apps[studentId];
    if (!app || app.status !== "submitted" || !app.review) {
      return { success: false, message: "申请不存在或未提交" };
    }
    const order = ["collegeHouse", "college", "university"];
    const current = app.review.stage || "collegeHouse";
    const idx = order.indexOf(current);
    if (idx === -1) return { success: false, message: "阶段错误" };
    if (action === "approve") {
      app.review.stages[current].status = "approved";
      if (idx < order.length - 1) {
        app.review.stage = order[idx + 1];
      } else {
        app.status = "completed";
      }
    } else if (action === "reject") {
      app.review.stages[current].status = "rejected";
      app.status = "rejected";
    }
    app.updatedAt = new Date().toISOString();
    apps[studentId] = app;
    write(STORAGE_KEYS.APPLICATIONS, apps);
    return { success: true, message: "操作成功" };
  },
  getJudgeStatsByDepartment: function (department) {
    const user = getCurrentUser();
    if (!user || user.userType !== "judge") return { success: true, data: {} };
    const apps = read(STORAGE_KEYS.APPLICATIONS, {});
    const restrictStage = department ? this._deptToStage(department) : null;
    let total = 0,
      pending = 0,
      completed = 0,
      sum = 0,
      count = 0;
    Object.keys(apps).forEach((sid) => {
      const a = apps[sid];
      const status = a.status || "draft";
      const stage = a.review?.stage || "collegeHouse";
      if (status === "draft") return;
      if (restrictStage && status === "submitted" && stage !== restrictStage)
        return;
      if (restrictStage && status === "submitted") {
        const stageOrder = ["collegeHouse", "college", "university"];
        const currentIndex = stageOrder.indexOf(stage);
        if (currentIndex > 0) {
          const prevStage = stageOrder[currentIndex - 1];
          const prevStatus = a.review?.stages?.[prevStage]?.status;
          if (prevStatus !== "approved") return;
        }
      }
      total++;
      if (status === "submitted") pending++;
      else if (status === "completed") completed++;
      if (a.scores && a.scores.total) {
        sum += a.scores.total;
        count++;
      }
    });
    const avgScore = count > 0 ? Math.round((sum / count) * 100) / 100 : 0;
    return { success: true, data: { total, pending, completed, avgScore } };
  },
  getJudgeApplicationDetail: function (studentId) {
    const user = getCurrentUser();
    if (!user || user.userType !== "judge")
      return { success: false, data: null };
    const apps = read(STORAGE_KEYS.APPLICATIONS, {});
    const users = read(STORAGE_KEYS.USERS, []);
    const app = apps[studentId];
    if (!app) return { success: false, message: "申请不存在" };
    const student = users.find((u) => u.id === studentId) || {};
    const status = app.status || "draft";
    const stage = app.review?.stage || "collegeHouse";
    const stageStatus = app.review?.stages?.[stage]?.status || "pending";
    let statusText = "";
    if (status === "completed") statusText = "已评审";
    else if (status === "rejected") statusText = "已退回";
    else if (status === "submitted")
      statusText = stageStatus === "pending" ? "待评审" : "进行中";
    else if (status === "draft") statusText = "草稿";
    else statusText = status;
    const courses = Array.isArray(app.transcript?.courses)
      ? app.transcript.courses
      : [];
    const excellentCount = courses.filter(
      (c) => (parseFloat(c.score) || 0) >= 90
    ).length;
    return {
      success: true,
      data: {
        student: {
          name: student.realName || student.username || "",
          studentId: student.username || "",
          major: (student.profile && student.profile.major) || "",
          grade: (student.profile && student.profile.grade) || "",
          gpa: app.transcript?.gpa || 0,
        },
        transcript: {
          gpa: app.transcript?.gpa || 0,
          totalCredits: app.transcript?.totalCredits || 0,
          courseCount: courses.length,
          excellentCount,
          courses,
        },
        research: (Array.isArray(app.research) ? app.research : []).map(
          (r) => ({
            id: r.id,
            title: r.title,
            type: r.type,
            typeName: r.type,
            role: r.role || "成员",
            date: r.date || "",
            description: r.description || "",
            files: r.files || [],
          })
        ),
        progress: [
          {
            name: "书院审核",
            status: app.review?.stages?.collegeHouse?.status || "pending",
          },
          {
            name: "学院审核",
            status: app.review?.stages?.college?.status || "pending",
          },
          {
            name: "学校审核",
            status: app.review?.stages?.university?.status || "pending",
          },
        ],
      },
    };
  },
  computeAutoScore: function (studentId) {
    const apps = read(STORAGE_KEYS.APPLICATIONS, {});
    const app = apps[studentId] || { transcript: null, research: [] };
    const t = app.transcript || { gpa: 0, courses: [], totalCredits: 0 };
    const courses = Array.isArray(t.courses) ? t.courses : [];
    const research = Array.isArray(app.research) ? app.research : [];
    const baseAcademic = Math.min(
      80,
      Math.round(((parseFloat(t.gpa) || 0) / 4) * 80)
    );
    const excellentCount = courses.filter(
      (c) => (parseFloat(c.score) || 0) >= 90
    ).length;
    const excellentRatio =
      courses.length > 0 ? excellentCount / courses.length : 0;
    const boost = Math.min(10, Math.round(excellentRatio * 10));
    const academic = Math.min(80, baseAcademic + boost);
    const researchSum = research.reduce(
      (s, r) => s + (parseFloat(r.score) || 0),
      0
    );
    const researchScore = Math.min(20, Math.round(researchSum));
    const total = academic + researchScore;
    return {
      academic,
      research: researchScore,
      total,
      breakdown: {
        baseAcademic,
        boost,
        excellentCount,
        courseCount: courses.length,
      },
    };
  },
  // Judge detail helper
};
